<template>
  <div>
    <!-- Form 表单组件。由输入框、选择器、单选框、多选框等控件组成，用以收集、校验、提交数据。 -->
    <el-form :inline="true" class="demo-form-inline" :model="cForm">
      <el-form-item label="一级分类" label-width="80px">
        <el-select v-model="cForm.category1Id" placeholder="请选择" @change="getCategory2List()">
          <el-option v-for="(c1, index) in list1" :key="c1.id" :label="c1.name" :value="c1.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类" label-width="80px">
        <el-select v-model="cForm.category2Id" placeholder="请选择" @change="getCategory3List()">
          <el-option v-for="(c2, index) in list2" :key="c2.id" :label="c2.name" :value="c2.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类" label-width="80px">
        <el-select v-model="cForm.category3Id" placeholder="请选择" @change="shareCategory3Id()">
          <el-option v-for="(c3, index) in list3" :key="c3.id" :label="c3.name" :value="c3.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'CategorySelectorView',
  data() {
    return {
      // 一级分类列表数据
      list1: [],
      // 二级分类列表数据
      list2: [],
      // 三级分类列表数据
      list3: [],
      cForm: {
        category1Id: '',
        category2Id: '',
        category3Id: ''
      }
    }
  },
  mounted() {
    this.getCategory1List()
  },
  methods: {
    async getCategory1List() {
      const result = await this.$API.attribute.reqCategory1List()
      if (result.code === 200) {
        this.list1 = result.data
      }
    },
    async getCategory2List() {
      this.list2 = []
      this.list3 = []
      this.cForm.category2Id = ''
      this.cForm.category3Id = ''
      const { category1Id } = this.cForm
      // 子组件向父组件传递，通过$emit事件通信。对象参数{ categoryId, level }
      this.$emit('getCategoryId', { categoryId: category1Id, level: 1 })
      const result = await this.$API.attribute.reqCategory2List(category1Id)
      if (result.code === 200) {
        this.list2 = result.data
      }
    },
    async getCategory3List() {
      this.list3 = []
      this.cForm.category3Id = ''
      const { category2Id } = this.cForm
      // 子组件向父组件传递，通过$emit事件通信。对象参数{ categoryId, level }
      this.$emit('getCategoryId', { categoryId: category2Id, level: 2 })
      const result = await this.$API.attribute.reqCategory3List(category2Id)
      if (result.code === 200) {
        this.list3 = result.data
      }
    },
    shareCategory3Id() {
      const { category3Id } = this.cForm
      // 子组件向父组件传递，通过$emit事件通信。对象参数{ categoryId, level }
      this.$emit('getCategoryId', { categoryId: category3Id, level: 3 })
    }
  }
}
</script>

<style scoped>

</style>
